import React, { Component } from 'react'
import { connect } from 'dva';
import { Form, Input, Button, notification, Cascader, Row, Icon, Modal, Tooltip } from 'antd';

import Build from './Build';
import Tag from './Tags';
import { DropDownSelect } from '@/components/DropDownSelect/index';
import { DividerItem, FormDivider } from '@/components/DividerItem';

import { FormComponentProps, UmiComponentProps, BaseComponentProps } from "@/common/type";
import { inject_unount } from '@/utils/middleware';
import { checkPhone, checkNoChinese } from '@/utils/inputCheck';
import { dealElement } from '@/utils/util';

import { DICT } from '../enum';

import { SearchCol, SearchRow } from '@/styled/form';
import styles from '@/styled/form.less';
import { MyButton } from '../styled';

const { confirm } = Modal;

interface P {
  data?: {
    id: string;
    cameraBrand: string;
    cameraProduct: string;
    cameraBrandName: string;
    cameraProductName: string;
    cameraSn: string;
    isCamera: Boolean | number;
    name: string;
    location: string;
    manager: string;
    mobile: string;
    telephone: string;
    builds: Array<{ name: string, id: string, fireRoomId?: string }>;
    cameraAddr: string;
    cameraProtocol: string;
  };
  sub?: any;
  brand?: Array<any>;
  buttons?: Array<any>;
  key?: number;
}

type Props = P & FormComponentProps & UmiComponentProps & BaseComponentProps;

@connect(({ fireroom, brand }) => ({
  dict: fireroom.dict,
  brand: brand.brand,
  sub: brand.sub,
  locationData: fireroom.locationData || {},
  optionData: fireroom.optionData || {},
  areaData: fireroom.areaData || {},
  cond: fireroom.cond
}))
@inject_unount
class FormItem extends Component<Props, any> {
  state = {
    confirmDirty: false,
    autoCompleteResult: [],
    isNew: true,
    brandOption: this.props.brand || [],
    option: [],
    isCamera: true,
    camera: [],
    show: false,
    brandName: null,
    tags: [],
    tmp: null,
  };
  formRef: any;

  componentDidMount() {
    const { data, form, dispatch } = this.props;
    let flag = false;
    dispatch({ type: 'fireroom/queryDict', payload: { keyList: DICT } });

    if (data) {
      const {
        id, isCamera, cameraAddr, cameraBrand, cameraProduct,
        cameraSn, cameraBrandName, cameraProductName, builds,
        ...items
      } = data;

      const sn = cameraSn ? cameraSn.split('://') : [];
      const camera = {
        cameraAddr,
        cameraSn: sn[sn.length - 1],
        cameraProtocol: sn[sn.length - 2] ? sn[sn.length - 2] : 'lecheng'
      }

      form.setFieldsValue({
        ...(isCamera ? camera : {}),
        ...items,
      })

      this.setState({
        brandName: cameraBrandName && cameraProductName ? `${cameraBrandName}/${cameraProductName}` : '',
        camera: [cameraBrand, cameraProduct],
        tags: Array.isArray(builds) ? builds.map(v => ({ ...v, fireRoomId: data.id })) : [],
        isCamera: !!(+isCamera),
      });
    }

    if (flag === false) {
      dispatch({
        type: 'brand/queryBrandList',
        payload: {
          type: '5'
        }
      }).then(() => {
        this.setState({
          brandOption: this.props.brand
        })
      })
    }
  }

  private handleSubmit = (e) => {
    e.preventDefault();

    const { form, data, dispatch } = this.props;
    const { camera, tags, isCamera } = this.state;

    form.validateFields((err, values) => {
      if (!err) {
        const { cameraProtocol, cameraSn, ...res } = values;
        const { cameraBrand, cameraProduct } = data || {};

        if (!!isCamera && !(
          (data && data.id && cameraBrand && cameraBrand) || 
          (Array.isArray(camera) && camera.length === 2)
         )
        ) {
          notification['error']({
            message: `保存失败`,
            description: '字段验证不通过',
          });
          return;
        }

        const ans = dealElement({
          ...res,
          cameraProtocol,
          cameraSn: cameraProtocol && cameraSn ? `${cameraProtocol}://${cameraSn}` : null,
          cameraBrand: camera && Array.isArray(camera) ? camera[0] || cameraBrand : cameraBrand,
          cameraProduct: camera && Array.isArray(camera) ? camera[1] || cameraProduct : cameraProduct,
          buildIds: Array.isArray(tags) ? tags.map(v => v && v.id) : [],
          isCamera: +isCamera,
        });

        data && data.id ? dispatch({
          type: 'fireroom/update',
          payload: {
            id: data.id,
            ...ans
          }
        }).then(() => {
          notification.success({
            message: '保存成功',
            description:
              '修改消控室成功',
          });
        })
         : dispatch({
          type: 'fireroom/create',
          payload: ans
        }).then(() => {
          notification.success({
            message: '保存成功',
            description:
              '新增消控室成功',
          });
        
        })
      } else {
        notification['error']({
          message: `保存失败`,
          description: '字段验证不通过',
        });
      }
    })
  }

  private cameraLoadData = (selectedOptions) => {
    const { dispatch, brand } = this.props;
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;

    if (+targetOption.value < 1e8) {
      dispatch({ type: 'brand/queryProductNum', payload: targetOption.value }).then(() => {
        targetOption.loading = false;
        targetOption.children = this.props.sub;
        const op = this.state.brandOption || brand;
        this.setState({
          brandOption: [...op],
        });
      })
    }
  }

  saveFormRef = formRef => {
    this.formRef = formRef;
  };


  private onChangeCameraCascader = (value) => {
    this.setState({
      camera: value,
    })
  }

  private switchOnChange = (checked) => {
    this.setState({ isCamera: checked }, () => {
      const { data, form } = this.props;
      if (data) {
        const { cameraAddr, cameraSn, cameraBrandName, cameraProductName, cameraBrand, cameraProduct } = data;

        const sn = cameraSn ? cameraSn.split('://') : [];
        const camera = {
          cameraAddr,
          cameraSn: sn[sn.length - 1],
          cameraProtocol: sn[sn.length - 2] ? sn[sn.length - 2] : 'lecheng',
        }

        form.setFieldsValue({
          ...(checked ? camera : {})
        })

        this.setState({
          brandName: cameraBrandName && cameraProductName ? `${cameraBrandName}/${cameraProductName}` : '',
          camera: [cameraBrand, cameraProduct],
        });
      }
    })
  }

  private checkDispatch = (cur, pre) => {
    return Array.isArray(cur) && cur.some(v => +v.fireRoomId !== 0 && v.fireRoomId !== pre)
  }

  private handleSelect = () => {
    const { tmp, tags } = this.state;
    const { data } = this.props;

    this.checkDispatch(tmp, data ? data.id : 0)
      ? confirm({
        title: '管辖范围',
        content: '所选建筑中包含已有所属消控室的建筑，确认后将会改变所属消控室，是否继续？',
        okText: '继续',
        cancelText: '取消',
        onOk: () => {
          this.setState({ show: false, tags: !!tmp ? tmp : tags })
        },
      })
      : this.setState({ show: false, tags: !!tmp ? tmp : tags })
  }

  private handleCancel = v => {
    const { dispatch } = this.props;
    dispatch({ type: 'fireroom/setBuildCond', payload: {} })
    this.setState({ show: false })
  }

  private handleClose = removedTag => {
    const tags = this.state.tags.filter(tag => tag !== removedTag);
    this.setState({ tags })
  };

  private handleSelectRow = (rows) => {
    const { dispatch } = this.props;
    dispatch({ type: 'fireroom/setBuildCond', payload: {} })
    this.setState({ tmp: rows })
  }

  render() {
    const { form, dict = {}, data } = this.props;
    const { isCamera, tags = [] } = this.state;

    const { getFieldDecorator } = form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 8 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 12 },
        sm: { span: 14 },
      },
    };

    const prefixCameraProtocol = getFieldDecorator('cameraProtocol', {
      initialValue: 'lecheng',
    })(
      (DropDownSelect(dict, 'camera.protocol', '', '90px'))
    );

    const Details = DividerItem("appstore", '消控室信息')
    const Robot = FormDivider("robot", '摄像头', isCamera, this.switchOnChange);

    return (
      <Form onSubmit={this.handleSubmit}>
        <Modal
          title={<span style={{ color: 'rgba(0, 0, 0, 0.9)', fontWeight: 400, fontSize: '20px' }}>管辖区域</span>}
          width={800}
          style={{ top: 20 }}
          visible={this.state.show}
          onOk={this.handleSelect}
          onCancel={this.handleCancel}
          destroyOnClose
          okText="确认"
          cancelText="取消"
        >
          <Build
            wrappedComponentRef={this.saveFormRef}
            fireRoomId={data ? data.id : null}
            isSelect={true}
            onSelectRow={this.handleSelectRow}
            selected={Array.isArray(tags) ? tags.map(v => `${v.id}%%${v.name}%%${v.fireRoomId}`) : []}
          />
        </Modal>
        <Details />
        <SearchRow>
          <SearchCol span={11}>
            <Form.Item
              {...formItemLayout}
              label='消控室地址'
              className={styles.fileRequire}
            >
              {getFieldDecorator('name', {
                rules: [{ required: true, message: '请输入消控室地址' }],
              })(
                <Input style={{ width: '100%' }} placeholder='请输入消控室地址' />
              )}
            </Form.Item>
          </SearchCol>
          <SearchCol span={11} offset={2}>
            <Form.Item
              {...formItemLayout}
              label='责任人'
            >
              {getFieldDecorator('manager', {
                rules: [{ required: true, message: '请输入责任人' }],
              })(
                <Input style={{ width: '100%' }} placeholder='请输入责任人' />
              )}
            </Form.Item>
          </SearchCol>
        </SearchRow>
        <SearchRow>
          <SearchCol span={11}>
            <Form.Item
              {...formItemLayout}
              label='值班电话'
            >
              {getFieldDecorator('telephone', {
                rules: [{ required: true, message: '请检查', min: 10 },
                { validator: checkNoChinese }],
              })(
                <Input style={{ width: '100%' }} placeholder='请输入区号和电话号码' />
              )}
            </Form.Item>
          </SearchCol>
          <SearchCol span={11} offset={2}>
            <Form.Item
              {...formItemLayout}
              label='手机号'
            >
              {getFieldDecorator('mobile', {
                rules: [{ required: true, message: '请输入联系电话' }, { validator: checkPhone }],
              })(
                <Input style={{ width: '100%' }} placeholder='请输入联系电话' />
              )}
            </Form.Item>
          </SearchCol>
        </SearchRow>
        <SearchRow>
          <SearchCol span={11}>
            <Form.Item
              {...formItemLayout}
              label='管辖范围'
            >
              <MyButton onClick={() => this.setState({ show: true })}>
                <Icon type="check-square" />选择范围</MyButton>
              <span style={{ display: 'inline-block', marginLeft: '5px' }}>{this.state.show}</span>
              <Row>
                {tags.map((tag, index) => {
                  const isLongTag = tag.name.length > 12;
                  const tagElem = (
                    <Tag
                      key={tag.id} closable={true}
                      onClose={this.handleClose.bind(this, tag)}
                      data={{ ...tag, name: isLongTag ? `${tag.name.slice(0, 20)}...` : tag.name }}
                    />
                  );
                  return isLongTag ? (
                    <Tooltip title={tag.name} key={tag.id}>
                      {tagElem}
                    </Tooltip>
                  ) : tagElem;
                })}
              </Row>
            </Form.Item>
          </SearchCol>
          <SearchCol span={11} offset={2}></SearchCol>
        </SearchRow>
        <Robot />
        {
          isCamera && <>
            <SearchRow>
              <SearchCol span={11}>
                <Form.Item
                  {...formItemLayout}
                  label='摄像头S/N'
                >
                  {getFieldDecorator('cameraSn', {
                    rules: [{ required: true, message: '请输入摄像头SN', whitespace: true }],
                  })(
                    <Input addonBefore={prefixCameraProtocol} style={{ width: '100%' }} placeholder='请输入摄像头S/N' />
                  )}
                </Form.Item>
              </SearchCol>
              <SearchCol span={11} offset={2}>
                <Form.Item
                  {...formItemLayout}
                  label='摄像头型号'
                  className={styles.fileRequire}
                >
                  {getFieldDecorator('camera')(
                    <Cascader
                      options={this.state.brandOption || this.props.brand}
                      loadData={this.cameraLoadData}
                      changeOnSelect
                      placeholder={this.state.brandName || "请选择"}
                      onChange={this.onChangeCameraCascader}
                    />
                  )}
                </Form.Item>
              </SearchCol>
              <SearchCol span={11}>
                <Form.Item
                  {...formItemLayout}
                  label='直播地址'
                >
                  {getFieldDecorator('cameraAddr', {
                    rules: [{ required: true, message: '请输入直播地址', whitespace: true }],
                  })(
                    <Input style={{ width: '100%' }} placeholder='请输入直播地址' />
                  )}
                </Form.Item>
              </SearchCol>
              <SearchCol span={11} offset={2}></SearchCol>
            </SearchRow>
          </>
        }
        <Row style={{ position: 'absolute', left: '18%', bottom: '50px', width: '500px' }} type="flex" >
          <Button onClick={() => window.history.back()}>取消</Button>
          <Button type="primary" htmlType="submit" style={{ marginLeft: '5%' }} >保存</Button>
        </Row>
      </Form>
    );
  }
}

const FormList = Form.create<Props>()(FormItem);
export default FormList;
